import re
from flask import Blueprint,request,jsonify
import json
import jinja2
from werkzeug.security import generate_password_hash,check_password_hash
from db import db1
from flask_mail import Mail,Message
from flask import current_app as app
from werkzeug.utils import redirect
bp_user=Blueprint('user',__name__)
import datetime
import random

def send_mail(title,email,content):
    mail = Mail(app)
    msg = Message(title,sender='c1061418032@163.com',recipients=[email])
    msg.html = content
    mail.send(msg)

@bp_user.route('/reg',methods=['POST'])
def reg():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    sql= "insert into users(nikename,password,email) values('%s','%s','%s')"%(data['nikename'],generate_password_hash(data['password']),data['email'])
    db1.update(sql)
    send_mail('欢迎使用',data['email'],"欢迎使用，点击以下<a href='http://localhost:5000/user/validEmail?email="+data['email']+"'>链接</a>验证")

    return jsonify({'code':200})


@bp_user.route('validEmail')
def validEmail():
    email = request.args.get('email')
    sql = "update users set status=1 where email='%s'"%(email)
    db1.update(sql)
    return redirect('http://localhost:8888')



@bp_user.route('getcate')
def getcate():
    sql = "select id,name from cates"
    res= db1.findall(sql)
    return jsonify({'code':200,'list':res})


import math
@bp_user.route('getcourses')
def getcourses():
    
    page = int(request.args.get('page'))
    page_size=2
    start = (page-1)*int(page_size)
    status = request.args.get('course_type')
    if status:
        where = ' where status='+status
    online = request.args.get('status')
    if online:
        where = ' where online='+str(online)
    pid = request.args.get('course_tag')
    if pid :
        where = " where pid="+pid
    ordering = request.args.get('ordering')
    if ordering=='-create_time':
        where = where + ' and is_new=1'
    elif ordering=='-learner':
        where = where + ' and is_hot=1'
    sql = "select * from courses"+where+" limit %d,%d"%(start,int(page_size))
    print(sql)
    res = db1.findall(sql)
    sql1 = "select count(id) as c from courses"+where
    total = db1.find(sql1)
    # 计算总页数
    tcount = math.ceil(total['c']/int(page_size))
    return jsonify({'code':200,'list':res,'total':tcount})

import requests

@bp_user.route('/weiboCallback/')
def weiboCallback():
    code = request.args.get('code')
    #微博认证地址
    access_token_url = "https://api.weibo.com/oauth2/access_token"
    #参数
    response = requests.post(access_token_url,data={
        "client_id": '3648830690',
        "client_secret": "916d80b477ccffce5d70e63b02bb1092",
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": "http://127.0.0.1:8000/users/weiboCallback/",
    })
    res = eval(str(response.text))
    try:
        uid = res['uid']
        token = res['token']
    except:
        uid=0
        # 跳转为错误页面
        return redirect('http://localhost:8888/error')
    # 通过uid去第三方登录表查询
    sql = "select userid from sf_login as sf inner join users as u on sf.userid=uid where uid=%d"%(int(uid))
    res  = db1.find(sql)
    if res:
        return redirect('http://localhost:8888/bindMbile?type=1&id='+res['id']+'&name='+res['name'])
    else:
        # 不存在绑定用户操作，跳转到vue页面，uid，token，webfrom
        return redirect('http://localhost:8888/bindMbile?type=2&uid='+uid+'&token='+token)


@bp_user.route('/bindmobile',methods=['POST','GET'])
def bindmobile():
    if request.method=='POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "select id from users where email='%s'"%(data['mobile'])
        email = db1.find(sql)
        if email:
            return jsonify({'code':10010,'mes':'邮箱已经存在'})
        else:
            sql = "insert into users(email) values('%s')"%(data['mobile'])
            res = db1.update(sql)
            # 查询id
            sql1 = "select id from users where email='%s'"%(data['mobile'])
            user = db1.find(sql1)
            # 第三方登录表中添加信息
            sql2 = "inser into ssf_login(user_id,platfrom,uid,token) values(%d,'weibo','%s','%s')"%(int(user['id'],data['uid'],data['token']))
            db1.update(sql2)
            return jsonify({'code':200,'id':user['id'],'name':data['mobile']})
    else:
        return  'ok'



from utils.comm import get_ali_object
import time
@bp_user.route('/pay')
def pay():
    order = request.args.get('id')
    sql="select * from active_record where id=%d"%(int(order))
    res = db1.find(sql)
    
    
    alipay = get_ali_object()
    # 生成支付的url
    query_params = alipay.direct_pay(
        subject="test",  # 商品简单描述
        out_trade_no='active:'+str(res['id']),
        total_amount=float(res['price']),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({'code':200,'url':pay_url})


@bp_user.route('/notify/')
def notify():
     #支付的时候传递给支付宝的订单号
    out_trade_no = request.args.get('out_trade_no')
    #支付宝的流水号
    trade_no = request.args.get('trade_no')
    orderlist = out_trade_no.split(':')
    if orderlist[0]=='active':
 
        #根据out_trade_no 查询 记录表active_record
        sql = "select * from active_record where id=%d"%(int(out_trade_no))
        res = db1.find(sql)
        if res:
            #更新支付状态为2，流水号为trade_no
            sql2 = "update active_record set pay_status=2,snumber='%s' where id=%d"%(str(trade_no),int(out_trade_no))
            db1.update(sql2)
            #更新活动可用次数-1
            #根据活动id查询活动信息
            sql1 = "select * from active where id=%d"%(int(res['active_id']))
            res1 = db1.find(sql1)
            if int(res1['use_count'])>=1:
                    count = int(res1['use_count'])-1
                    sql2 = "update active set use_count=%d where id=%d"%(count,int(out_trade_no))
                    db1.update(sql2)
                    return redirect('http://localhost:8888')
    elif orderlist[0]=='vip':
        sql = "select vip_price.type as type,vip_order.userid as userid from vip_order inner join vip_price on vip_order.vip_id=vip_price.id where order_on=%d"%(int(out_trade_no))
        res = db1.find(sql)
        #更新支付状态为1，流水号为trade_no
        sql1 = "update vip_order set pay_status=1,transaction='%s' where order_on='%s'"%(str(trade_no),out_trade_no)
        db1.update(sql1)
        # 修改用户的等级
        sql2 = "update users set level=% d where id=%d"%(int(res['type']),int(res['userid']))
        db1.update(sql2)
        if int(res['type']) != 3:
            sql3 = "select * from vip_order_record where userid=%d and type=1"%(int(res['userid']))
            res3 = db1.find(sql3)
            if res3:
                # 更新时间
                pass
            else:
                start = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d')
                if int(res['type'])==2:
                    year = datetime.datetime.strftime(datetime.datetime.now(),'%Y')
                    newyear= year+1
                    month = datetime.datetime.strftime(datetime.datetime.now(),'%m-%d')
                    end = '{}-{}'.format(newyear,month)
                    sql4 = "insert into vip_order_record(stime,etime,type,userid) values('%s','%s',1,%d)"%(start,end,int(res['userid']))
                    db1.update(sql4)
                elif int(res['type'])==4:
                # 添加
                    pass
                
        return redirect('http://localhost:8888/vip')

@bp_user.route('/vip_list')
def vip_list():
    sql="select * from vip_price order by type asc"
    res=db1.findall(sql)
    return jsonify({'code':200,'list':res})


@bp_user.route('/create_order')
def create_order():
    id = request.args.get('id')
    userid = request.args.get('userid')
    if not all([id,userid]):
        return jsonify({'code':20010,'mes':'参数不对'})
    sql = "select * from vip_price where id=%d"%(int(id))
    res = db1.find(sql)
    order_on = datetime.datetime.strftime(datetime.datetime.now(),"%Y%m%d%H%M%S")+str(userid)+str(random.randint(10000,99999))
    sql1 = "insert into vip_order(userid,order_on,vip_id,money,pay_status) values(%d,'%s',%d,%d,1)"%(int(userid),order_on,int(id),int(res['money']))
    print(sql1)
    db1.update(sql1)
    alipay = get_ali_object()
    # 生成支付的url
    query_params = alipay.direct_pay(
        subject="test",  # 商品简单描述
        out_trade_no='vip:'+str(res['id']),
        total_amount=res['money'],  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({'code':200,'url':pay_url})